﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Nox.Amuse.Helpers;
using System.ComponentModel;

namespace Nox.Amuse.Model
{
    [XmlRoot("World")]
    public class WorldData : IDataErrorInfo
    {
        /// <summary>
        /// The file name template for this class to be saved under when serialized
        /// </summary>
        const string FileName = "{0} - World.xml";

        public string Name { get; set; }

        public string Address { get; set; }

        public int Port { get; set; }

        public double InputHeight { get; set; }


        /// <summary>
        /// Attempts to Load settings from the disk and push them in to a new instance. If file is not found, loads defaults.
        /// </summary>
        /// <returns>A new settings model</returns>
        public static WorldData Load(string Name)
        {
            var serializer = new XmlSerializer(typeof(WorldData));
            var textReader = FileHelper.StartReadingTextFile(String.Format(FileName, Name));
            if (textReader != null)
            {
                try
                {
                    return (WorldData)serializer.Deserialize(textReader);
                }
                catch
                {
                    return new WorldData();
                }
                finally
                {
                    textReader.Close();
                }
            }
            else
                return new WorldData();
        }

        public WorldData()
        {
            this.Name = "Untitled";
            this.Port = 23;
        }

        /// <summary>
        /// Saves the data
        /// </summary>
        public void Save()
        {
            var serializer = new XmlSerializer(typeof(WorldData));
            var writer = FileHelper.StartWritingTextFile(String.Format(FileName, Name));
            serializer.Serialize(writer, this);
            writer.Close();
        }

        [XmlIgnore]
        public string Error
        {
            get { return null; }
        }

        [XmlIgnore]
        public string this[string propertyName]
        {
            get
            {
                switch (propertyName)
                {
                    case "Port":
                        if (Port < 1 || Port > (Int16.MaxValue * 2) + 1)
                            return "A port number must be no less than 1 and no greater than 65535.";
                        return null;
                    default:
                        return null;
                }
            }
        }

        internal void Delete()
        {
            FileHelper.Delete(String.Format(FileName, Name));
        }
    }
}
